const { Sequelize, DataTypes } = require('sequelize');

// 数据库配置
const sequelize = new Sequelize({
  dialect: 'mysql',
  host: 'localhost',
  port: 3306,
  username: 'root',
  password: '888mei525',
  database: 'lingxi_system',
  logging: false
});

// 定义销售订单模型
const SalesOrderModel = sequelize.define('sales_order', {
  id: {
    type: DataTypes.BIGINT,
    primaryKey: true,
    autoIncrement: true
  },
  platformOrderId: {
    type: DataTypes.STRING(200),
    allowNull: false,
    unique: true,
    field: 'platform_order_id'
  },
  orderAmount: {
    type: DataTypes.DECIMAL(12, 2),
    allowNull: false,
    field: 'order_amount'
  }
}, {
  tableName: 'sales_orders',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at'
});

// 定义销售订单项模型
const SalesOrderItemModel = sequelize.define('sales_order_item', {
  id: {
    type: DataTypes.BIGINT,
    primaryKey: true,
    autoIncrement: true
  },
  orderId: {
    type: DataTypes.BIGINT,
    allowNull: false,
    field: 'order_id'
  },
  productName: {
    type: DataTypes.STRING(200),
    allowNull: false,
    field: 'product_name'
  },
  quantity: {
    type: DataTypes.INTEGER,
    allowNull: false
  },
  amount: {
    type: DataTypes.DECIMAL(12, 2),
    allowNull: false
  }
}, {
  tableName: 'sales_order_items',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at'
});

// 建立模型关系
SalesOrderModel.hasMany(SalesOrderItemModel, {
  foreignKey: 'orderId',
  as: 'items'
});
SalesOrderItemModel.belongsTo(SalesOrderModel, {
  foreignKey: 'orderId',
  as: 'order'
});

async function checkCurrentData() {
  try {
    await sequelize.authenticate();
    console.log('数据库连接成功');
    
    // 检查销售订单表
    const orderCount = await SalesOrderModel.count();
    console.log(`销售订单表中有 ${orderCount} 条记录`);
    
    // 检查销售订单项表
    const itemCount = await SalesOrderItemModel.count();
    console.log(`销售订单项表中有 ${itemCount} 条记录`);
    
    // 获取所有订单及其项数
    const orders = await SalesOrderModel.findAll({
      attributes: ['id', 'platformOrderId', 'orderAmount'],
      include: [{
        model: SalesOrderItemModel,
        as: 'items',
        attributes: ['id', 'productName', 'quantity', 'amount']
      }],
      order: [['id', 'ASC']]
    });
    
    console.log('\n订单详情:');
    orders.forEach((order, index) => {
      console.log(`${index+1}. 订单ID: ${order.platformOrderId}`);
      console.log(`   订单金额: ${order.orderAmount}`);
      console.log(`   订单项数: ${order.items.length}`);
      order.items.forEach((item, itemIndex) => {
        console.log(`     ${itemIndex+1}) ${item.productName} - 数量: ${item.quantity}, 金额: ${item.amount}`);
      });
      console.log('');
    });
    
  } catch (error) {
    console.error('检查数据时出错:', error);
  } finally {
    await sequelize.close();
  }
}

checkCurrentData();